<template>
  <div class="components-platform-add-or-update">
    <el-dialog
      v-model="visible"
      width="900px"
      :title="!dataForm.formId ? $t('crud.addTitle') : $t('groups.edit')"
      :close-on-click-modal="false"
      class="dialog-box"
      @close="closeDialogHandle"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        label-width="110px"
        @submit.prevent
      >
        <el-form-item
          :label="$t('formData.reportName')"
          prop="formName"
        >
          <el-input
            v-model="dataForm.formName"
            :placeholder="$t('formData.pleaseEnterTheReportName')"
            maxlength="50"
            show-word-limit
            clearable
            @blur="dataForm.formName = onInputTrim(dataForm.formName)"
          />
        </el-form-item>
        <el-form-item
          :label="$t('formData.typeOfData')"
          prop="fromType"
        >
          <el-radio-group v-model="dataForm.fromType">
            <el-radio :label="1">
              {{ $t("formData.shop") }}
            </el-radio>
            <!-- <el-radio :label="2">商品</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="$t('formData.timePeriod')"
          prop="timeType"
        >
          <el-radio-group v-model="dataForm.timeType">
            <el-radio :label="1">
              {{ $t("formData.natureDay") }}
            </el-radio>
            <el-radio :label="2">
              {{ $t("formData.natureWeek") }}
            </el-radio>
            <el-radio :label="3">
              {{ $t("formData.naturalMoon") }}
            </el-radio>
          </el-radio-group>&nbsp;&nbsp;&nbsp;&nbsp;
          <el-tooltip
            class="item"
            effect="light"
            :content="$t('formData.accordingToTheSelectedType')"
            placement="top"
          >
            <span>
              <el-icon><QuestionFilled /></el-icon>
            </span>
          </el-tooltip>
        </el-form-item>
        <el-form-item
          :label="$t('formData.timeFormat')"
          prop="timeFormat"
        >
          <el-radio-group v-model="dataForm.timeFormat">
            <el-radio :label="1">
              {{ $t("formData.customTime") }}
            </el-radio>
            <el-radio :label="2">
              {{ $t("formData.specifyTimeRange") }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="dataForm.timeFormat === 1"
          :label="$t('formData.customTime')"
          prop="time"
        >
          <el-date-picker
            v-if="dataForm.timeType === 1"
            v-model="dataForm.time"
            type="daterange"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('date.start')"
            :end-placeholder="$t('date.end')"
            :shortcuts="shortcuts"
            :clearable="false"
            @input="daterangeChange"
          />
          <el-date-picker
            v-else-if="dataForm.timeType === 3"
            v-model="dataForm.time"
            type="monthrange"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('date.start')"
            :end-placeholder="$t('date.end')"
            :shortcuts="shortcuts"
            :clearable="false"
            @input="daterangeChange"
          />
          <el-date-picker
            v-else-if="dataForm.timeType === 2"
            v-model="week"
            format="YYYY [第] ww [周]"
            type="week"
            :clearable="false"
            :placeholder="$t('formData.selectWeek')"
            @input="daterangeChange"
          />
        </el-form-item>
        <el-form-item
          v-if="dataForm.timeFormat === 2"
          :label="$t('formData.timeLimit')"
          prop="timeRamge"
          style="width:500px;"
        >
          <el-input
            v-model="dataForm.timeRamge"
            :placeholder="$t('formData.pleaseEnterTheTime')"
          >
            <template #prepend>
              {{ $t("formData.near") }}
            </template>
            <template #append>
              {{ dataForm.timeType === 1?$t('formData.day'):dataForm.timeType === 2?$t('formData.week'):$t('formData.month') }}
              <el-tooltip
                class="item"
                effect="light"
                :content="$t('formData.timeTip')"
                placement="top"
              >
                <span>
                  <el-icon><QuestionFilled /></el-icon>
                </span>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          :label="$t('number')"
          prop="seq"
        >
          <el-input-number
            v-model="dataForm.seq"
            controls-position="right"
            :min="1"
            @change="onSeqChange"
          />
        </el-form-item>
        <el-form-item
          :label="$t('formData.selectIndicator')"
          prop="formItem"
        >
          <el-card class="box-card">
            <el-row style="width:100%">
              <el-col
                v-for="item in formItemList"
                :key="item.id"
                :span="4"
              >
                <el-link
                  :underline="false"
                  :type="item.select?'success':'default'"
                  class="buttonClick"
                  @click="selectItem(item.id)"
                >
                  {{ item.value }}
                </el-link>
              </el-col>
            </el-row>
          </el-card>
        </el-form-item>
        <el-form-item>
          <el-tag
            v-for="item in formItemListSelect"
            :key="item.id"
            closable
            class="tag"
            type="info"
            @close="selectItem(item.id)"
          >
            {{ item.value }}
          </el-tag>
        </el-form-item>
      </el-form>
      <template #footer>
        <div
          class="default-btn"
          @click="onClose()"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { getCurrentInstance } from 'vue'
import moment from 'moment'

const emit = defineEmits(['refreshDataList'])

const dataForm = ref({
  formId: 0,
  formName: '',
  fromType: 1,
  timeType: 1,
  timeFormat: 1,
  formItemIds: '',
  startTime: '',
  endTime: '',
  timeRamge: 1,
  time: '',
  seq: 1
})
const dataFormRef = ref(null)

const shortcuts = [
  {
    text: $t('formData.lastWeek'),
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: $t('formData.lastMonth'),
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: $t('formData.lastThreeMonths'),
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

const week = ref('')
const formItemList = ref([])
const formItemListSelect = ref([])
let isSubmit = true

// eslint-disable-next-line no-unused-vars
const validateNumber = (rule, value, callback) => {
  const reg = /[^\d]/
  if (reg.test(value)) {
    callback(new Error($t('formData.pleaseThan0')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  formName: [
    { required: true, message: $t('formData.theReportNameCannotBeEmpty'), trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: $t('formData.startTimeCannotBeEmpty'), trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: $t('formData.endTimeCannotBeEmpty'), trigger: 'blur' }
  ],
  timeRamge: [
    { required: true, message: $t('formData.timeRangeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ]
})

const visible = ref(false)
// 获取分类数据 formType true:推荐报表
const init = (id, fromType) => {
  visible.value = true
  dataForm.value.formId = id || 0
  nextTick(() => {
    dataForm.value.formName = ''
    dataForm.value.content = ''
    dataForm.value.fromType = 1
    dataForm.value.timeType = 1
    dataForm.value.timeFormat = 1
    dataForm.value.formItemIds = ''
    dataForm.value.timeRamge = 1
    dataForm.value.seq = 1
    dataForm.value.time = ''
    dataForm.value.startTime = ''
    dataForm.value.endTime = ''
    formItemListSelect.value = []
    dataFormRef.value.resetFields()
  })
  if (dataForm.value.formId) {
    // 获取产品数据
    http({
      url: http.adornUrl(`/admin/form/info/${dataForm.value.formId}`),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value = data
      if (fromType) {
        dataForm.value.recommendForm = fromType
        dataForm.value.formId = 0
      }
      dataForm.value.time = dataForm.value.startTime && dataForm.value.endTime ? [moment(dataForm.value.startTime, 'YYYY-MM-DD'), moment(dataForm.value.endTime, 'YYYY-MM-DD')] : []
      if (dataForm.value.timeType === 2 && dataForm.value.timeFormat === 1) {
        const oneDayTime = 24 * 60 * 60 * 1000
        week.value = moment(new Date(new Date(dataForm.value.startTime) + oneDayTime))
      }
      getFormItem()
    })
  } else {
    nextTick(() => {
      dataFormRef.value.resetFields()
      dataForm.value.recommendForm = fromType
      dataForm.value.imgUrl = ''
    })
    getFormItem()
  }
}
const onSeqChange = () => {
  if (!dataForm.value.seq) {
    dataForm.value.seq = 1
  }
}
/**
 * 获取报表项数据
 */
const getFormItem = () => {
  http({
    url: http.adornUrl('/admin/form/getFormItem'),
    method: 'get',
    params: http.adornParams({
      type: 1
    })
  }).then(({ data }) => {
    formItemList.value = data
    if (dataForm.value.formItemIds) {
      const ids = dataForm.value.formItemIds.split(',')
      formItemList.value.forEach(element => {
        if (ids.indexOf(element.id.toString()) > -1) {
          element.select = true
          formItemListSelect.value.push(element)
        }
      })
    }
  })
}
/**
 * 选择开始时间/结束时间触发事件
 */
const { proxy } = getCurrentInstance()
const daterangeChange = () => {
  proxy.$forceUpdate()
}
// 处理日期（周）数据
const setWeekNum = (e) => {
  const newTime = e.getTime()
  const day = e.getDay()
  const oneDayTime = 24 * 60 * 60 * 1000
  const fromTime = (newTime - day * oneDayTime) + oneDayTime
  const endTime = newTime + (7 - day) * oneDayTime
  const start = new Date(fromTime)
  const end = new Date(endTime)
  return [start, end]
}
/**
 * 选择报表项
 */
const selectItem = (id) => {
  formItemListSelect.value = []
  formItemList.value.forEach(element => {
    if (element.id === id) {
      element.select = !element.select
    }
    if (element.select) {
      formItemListSelect.value.push(element)
    }
  })
}
// 表单提交
const onSubmit = () => {
  dataForm.value.recommendForm = false
  if (dataForm.value.timeType === 2) {
    dataForm.value.time = week.value
  }
  dataFormRef.value.validate((valid) => {
    if (valid) {
      if (dataForm.value.timeFormat === 1 && !dataForm.value.time) {
        ElMessage.error($t('formData.timeCannotBeEmpty'))
        return
      }
      if (formItemListSelect.value.length < 1) {
        ElMessage.error($t('formData.pleaseSelectAnIndicator'))
        return
      }
      if (!isSubmit) {
        return true
      }
      if (dataForm.value.timeFormat === 1) {
        if (dataForm.value.timeType === 2) {
          const tempWeek = setWeekNum(new Date(week.value))
          dataForm.value.startTime = moment(tempWeek[0]).format('YYYY-MM-DD hh:mm:ss')
          dataForm.value.endTime = moment(tempWeek[1]).format('YYYY-MM-DD hh:mm:ss')
        } else {
          dataForm.value.startTime = moment(dataForm.value.time[0]).format('YYYY-MM-DD hh:mm:ss')
          dataForm.value.endTime = moment(dataForm.value.time[1]).format('YYYY-MM-DD hh:mm:ss')
        }
      }
      isSubmit = false
      dataForm.value.formItemIds = getFormItemIds()
      const param = dataForm.value
      http({
        url: http.adornUrl('/admin/form'),
        method: param.formId ? 'put' : 'post',
        data: http.adornData(param)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            isSubmit = true
            visible.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        isSubmit = true
      })
    }
  })
}
/**
 * 获取已选择的报表项id
 */
const getFormItemIds = () => {
  let ids = ''
  formItemListSelect.value.forEach(item => {
    ids = ids + item.id + ','
  })
  ids = ids.substring(0, ids.length - 1)
  return ids
}
// 关闭对话框回调
const closeDialogHandle = () => {
  dataFormRef.value.resetFields()
}
/**
 * 输入框纯空格处理
 */
const onInputTrim = (value) => {
  if (!value) return
  if (!value.trim()) {
    return value.trim()
  } else {
    return value
  }
}
/**
* 关闭弹窗
*/
const onClose = () => {
  visible.value = false
}

defineExpose({
  init
})

</script>
<style lang="scss" scoped>
.tag {
  margin: 0 10px 10px 0;
}
</style>
